<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="center" prop="id" v-if="false"/>
      <el-table-column label="订单编号" align="center" prop="purchaseOrderId" v-if="false"/>
      <!-- <el-table-column label="产品编号" align="center" prop="productId"  /> -->
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品单位" align="center" prop="productUnitName" />
      <el-table-column label="产品规格" align="center" prop="productStandards" />
      <el-table-column label="单价" align="center" prop="productPrice" />
      <el-table-column label="数量" align="center" prop="count" />
      <el-table-column label="总价" align="center" prop="totalPrice" />
    </el-table>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="订单项" name="purPurchaseOrderItem">
        <PurPurchaseOrderItemForm ref="purPurchaseOrderItemFormRef" :purchase-order-id="formData.id" :type="formType" :zdbh="formData.purchaseOrderId"/>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { PurPurchaseOrderApi, PurPurchaseOrderVO } from '@/api/erp/purpurchaseorder'
import { PurPurchaseOrderItemApi, PurPurchaseOrderItemVO } from '@/api/erp/purpurchaseorderitem'
import PurPurchaseOrderItemForm from './components/PurPurchaseOrderItemForm.vue'
import { SupplierSendOrderApi } from '@/api/erp/suppliersendorder'

/** ERP 采购单 表单 */
defineOptions({ name: 'PurPurchaseOrderForm' })

const loading = ref(false) // 列表的加载中
const list = ref<PurPurchaseOrderItemVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  purchaseOrderId: 0,
})


const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  purchaseOrderId: undefined,
  integrateId: undefined,
  isMainOrder: undefined,
  mainOrderId: undefined,
  orderTime: undefined,
  supplierId: undefined,
  totalPrice: undefined,
  remark: undefined,
  status: undefined,
  processInstanceId: undefined,
})

const formRules = reactive({
  purchaseOrderId: [{ required: true, message: '采购单编号-提交供应商采购单编号不能为空', trigger: 'blur' }],
  integrateId: [{ required: true, message: '一级库整合单编号不能为空', trigger: 'blur' }],
  isMainOrder: [{ required: true, message: '是否主单不能为空', trigger: 'blur' }],
  mainOrderId: [{ required: true, message: '主单编号不能为空', trigger: 'blur' }],
  orderTime: [{ required: true, message: '采购时间不能为空', trigger: 'blur' }],
  supplierId: [{ required: true, message: '供应商编号不能为空', trigger: 'blur' }],
  totalPrice: [{ required: true, message: '合计价格不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('purPurchaseOrderItem')
const purPurchaseOrderItemFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = "详情"
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    loading.value = true
    try {
      formData.value = await PurPurchaseOrderApi.getPurPurchaseOrder(id)
      queryParams.purchaseOrderId = id
      const data = await PurPurchaseOrderItemApi.getPurPurchaseOrderItemPage(queryParams)
      list.value = data.list
      total.value = data.total
    } finally {
      formLoading.value = false
      loading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  // await formRef.value.validate()
  // 校验子表单
  try {
    await purPurchaseOrderItemFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'purPurchaseOrderItem'
    return
  }

  // 获取子表数据
  const subTableData = purPurchaseOrderItemFormRef.value.getData()

  // 按 productId 分组
  const productMap = new Map()

  for (const item of subTableData) {
    if (!item.productId) continue // 跳过未选择产品的项
    if (!productMap.has(item.productId)) {
      productMap.set(item.productId, [])
    }
    productMap.get(item.productId).push(item)
  }

  // 检查每个 productId 下的 batch 是否重复
  for (const [productId, items] of productMap.entries()) {
    const batchSet = new Set()
    for (const item of items) {
      const batch = item.batch
      if (batch) {
        if (batchSet.has(batch)) {
          message.error(`产品 ID: ${productId} 存在重复批次：${batch}`)
          return
        }
        batchSet.add(batch)
      }
    }
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PurPurchaseOrderVO
    const data1 = {
      id: undefined, // 编号
      outOrderId: undefined, // 随货同行单编号
      integrateId: data.integrateId, // 一级库整合单编号
      purchaseOrderId: data.purchaseOrderId, // 采购单编号-提交供应商采购单编号
      supplierId: data.supplierId, // 供应商编号
      sendTime: Date ,// 发货时间
      totalPrice: data.totalPrice, // 合计价格，单位：元
      remark: data.remark, // 备注
      status: data.status, // 状态
      processInstanceId: data.processInstanceId, // 流程实例的编号
      supplierSendOrderItems:purPurchaseOrderItemFormRef.value.getData()
    }
    const type = purPurchaseOrderItemFormRef.value.formType

    if (type === '新增') {

      await SupplierSendOrderApi.createSupplierSendOrder(data1)
      message.success(t('common.createSuccess'))
    } else {
      await SupplierSendOrderApi.updateSupplierSendOrder(data1)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    purchaseOrderId: undefined,
    integrateId: undefined,
    isMainOrder: undefined,
    mainOrderId: undefined,
    orderTime: undefined,
    supplierId: undefined,
    totalPrice: undefined,
    remark: undefined,
    status: undefined,
    processInstanceId: undefined,
  }
  formRef.value?.resetFields()
}
</script>